import { toRaw } from "vue"
import Mock from "mockjs"

let domain: string = ""
if (import.meta.env.VITE_RUNTIME === "development") {
  domain = uni.getSystemInfoSync().uniPlatform === "web" ? "/api" : import.meta.env.VITE_API_BASE_API
} else {
  domain = import.meta.env.VITE_API_BASE_API
}

const listTotal = Mock.Random.integer(100, 200)

// 模拟请求数据
const mockRequest = (option: any) => {
  return new Promise((reslove, reject) => {
    try {
      const { url, data } = option
      let returnData: any

      if (["/home/list"].includes(url)) {
        returnData = Mock.mock({
          "code": 200,
          "message": "success",
          "data": {
            "list|20": [{
              "id": "@guid",
              "type": "@pick(['image', 'video'])",
              "imageSrc": "/static/images/img@integer(1, 3).png",
              "videoSrc": "https://www.runoob.com/try/demo_source/movie.mp4",
              "game": "@ctitle(3, 8)",
              "title": "@ctitle(20, 60)",
              "user": {
                "name": "@ctitle(3, 5)",
                "avatar": "@image('200x200', '#6cf')"
              },
              "like": "@integer(100, 1000)",
              "isLike": "@boolean"
            }],
            "total": data.total || listTotal
          }
        })
      }

      setTimeout(() => {
        reslove(returnData)
      }, 1000)
    } catch (error) {
      reject(error)
    }
  })
}

// 封装请求函数
const request = (option: any) => {
  return new Promise((reslove, reject) => {
    const { url, method = "get", data, banMessage = false } = option

    uni.request({
      url: domain + url,
      method: method.toLocaleUpperCase(),
      data: data && toRaw(data),
      success: (res: any) => {
        const data: any = res.data
        if (res.statusCode == 200 && data.code == 200) {
          reslove(data)
        } else {

          if (!banMessage) {
            uni.showToast({
              title: data.msg || "数据请求错误，请联系客服",
              icon: "none"
            })
          }

          reject(data.msg || "数据请求错误，请联系客服")
        }
      },
      fail: (err) => {
        if (!banMessage) {
          uni.showToast({
            title: err.errMsg || "数据请求错误，请联系客服",
            icon: "none"
          })
        }
        reject(err.errMsg || "数据请求错误，请联系客服")
      }
    })
  })
}

export default import.meta.env.VITE_MOCK ? mockRequest : request